﻿using LitJson;
using LNet;
using OestsCommon.Model;
using OestsDataBase;
using OestsServer.Managers;
using OestsServer.Net;
using System;
using System.Collections.Generic;

namespace OestsServer.Handlers.OESPHandlers
{
    public class LoginOespHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey
        {
            get
            {
                return PacketKey.Login;
            }
        }

        public override void Execute(OESPClientChannel client, Request packet)
        {
            ResponsePacket = new Response(packet);

            if (packet.RequestSubCode == SubCode.None)
            {
                LoginNone(client, packet);
            }

        }
        private void LoginNone(OESPClientChannel client, Request packet)
        {
            User u = JsonMapper.ToObject<User>(packet.DataStr);

            if (u.DBid > 0)//>0重新连接
            {
                //登录成功
                client.SetUserData(u);
                //client.UpdateLoginTime();
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Success;
                client.Send(ResponsePacket);

                return;
            }


            /////////////////// 获得 数据库中的 user/////////////////////
            User UserDB = UserDAL.GetUser(u.Number);//根据工号获取数据库中的对象

            /////////////////// 用户验证/////////////////////
            if (UserDB == null)
            {
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "用户不存在！";
                client.Send(ResponsePacket);
                return;
            }

            if (u.Password != UserDB.Password)
            {
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "密码错误！";
                client.Send(ResponsePacket);
                return;
            }

            //检查用户是否在线
            if (client.CheckUserIsExist(UserDB.DBid))
            {
                ResponsePacket.DataObject = u;
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "该用户已经在线！";
                client.Send(ResponsePacket);
                return;
            }

            //登录成功
            client.SetUserData(UserDB);
            client.UpdateLoginTime();
            ResponsePacket.DataObject = UserDB;
            ResponsePacket.ReturnCode = ReturnCode.Success;
            client.Send(ResponsePacket);
        }
    }
}